import { useMutation, useQuery, useQueryClient } from "react-query";
import { useHttp } from "utils/http";
import { Search } from "types/search";
import { useSearchParams } from "react-router-dom";
import { useUrlQueryParam } from "utils/url";
import { useMemo } from "react";

export const useNameInUrl = () => {
  const [params] = useSearchParams();
  return params.get("name");
};
export const useSearchName = () => ({ name: useNameInUrl() || undefined });
export const useSearchQueryKey = () => ["search", useSearchName()];

export const useAddSearch = () => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<Search>) =>
      client(`hot/add`, { data: params, method: "POST" }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useEditSearch = () => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<Search>) =>
      client(`hot/modify`, {
        data: params,
        method: "POST",
      }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useModifySearch = () => {
  const [{ id }] = useUrlQueryParam(["id"]);
  const { data: hot, isLoading } = useHot(Number(id));

  return {
    id,
    hot,
    isLoading,
  };
};

export const useSearch = (param?: Partial<Search>) => {
  const client = useHttp();

  return useQuery<Search[]>(["search", param], () =>
    client("hot/lists", { data: param })
  );
};

export const useHot = (id?: number) => {
  const client = useHttp();
  return useQuery<Search>(["hot", { id }], () => client(`hot/detail/${id}`), {
    enabled: !!id,
  });
};

export const useHotDel = (param?: Partial<Search>) => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<Search>) =>
      client(`hot/del`, {
        data: params,
        method: "POST",
      }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useHotsSearchParams = () => {
  const [param, setParam] = useUrlQueryParam(["name", "id"]);
  return [
    useMemo(() => ({ ...param, id: Number(param.id) || undefined }), [param]),
    setParam,
  ] as const;
};
